import { MongoClient, Filter } from 'mongodb';

const url = 'mongodb://root:MengJi950127@172.18.172.152:27017/?authSource=admin'; // MongoDB 服务器地址
const dbName = 'data_works'; // 数据库名称
const collectionName = 'patents'; // 集合名称
const idleTimeout = 3000; // 空闲超时时间，单位为毫秒

const client = new MongoClient(url);
let isConnected = false; // 连接状态标志
let idleTimer: ReturnType<typeof setTimeout> | null = null; // 空闲计时器

async function connectMongo() {
    if (!isConnected) {
        await client.connect();
        isConnected = true; // 更新连接状态
    }
    resetIdleTimer();
    return client.db(dbName).collection(collectionName);
}

function resetIdleTimer() {
    if (idleTimer) {
        clearTimeout(idleTimer);
    }
    idleTimer = setTimeout(() => {
        client.close();
        isConnected = false;
        console.log('MongoDB connection closed due to inactivity.');
    }, idleTimeout);
}

export async function upsertItem(item: any) {
    const collection = await connectMongo();
    const result = await collection.updateOne(
        { _id: item._id }, // 查找条件
        { $set: item }, // 更新内容
        { upsert: true } // 如果不存在则插入
    );
    resetIdleTimer();
    return result;
}

export async function queryItems(query: Filter<any>) {
    const collection = await connectMongo();
    const items = await collection.find(query).toArray();
    resetIdleTimer();
    return items;
}
